using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Paradogs2.api;
using Paradogs2;
using ProtoBuf;
using UnityEngine;

namespace pd2_server_sdk.server.demo
{
    [GameHandler]
    public class PDSdkHandler
    {
        // 错误消息
        [Route("_net.err")]
        public void err()
        {
            Debug.LogError("err");
        }

        // 状态同步消息
        [Route("_sync.owner")]
        public void SyncData(OwnerSyncData source)
        {
            if (PD2SdkContext.owner == null)
            {
                PD2SdkContext.owner = new OwnerSyncData();
            }

            FieldInfo[] fields = typeof(OwnerSyncData).GetFields(BindingFlags.Public | BindingFlags.Instance);

            foreach (FieldInfo field in fields)
            {
                // 处理 BaseEntity 子类字段
                if (typeof(BaseEntity).IsAssignableFrom(field.FieldType))
                {
                    SyncBaseEntityField(field, source, PD2SdkContext.owner);
                }
                // 处理 List<BaseMultiEntity子类> 字段
                else if (IsBaseMultiEntityList(field))
                {
                    SyncBaseMultiEntityList(field, source, PD2SdkContext.owner);
                }
            }
        }

        /// <summary>
        /// 判断字段是否为 List<BaseMultiEntity子类>
        /// </summary>
        private bool IsBaseMultiEntityList(FieldInfo field)
        {
            return field.FieldType.IsGenericType &&
                   field.FieldType.GetGenericTypeDefinition() == typeof(List<>) &&
                   typeof(BaseMultiEntity).IsAssignableFrom(field.FieldType.GetGenericArguments()[0]);
        }

        /// <summary>
        /// 同步 BaseEntity 子类字段（仅赋值非null字段）
        /// </summary>
        private void SyncBaseEntityField(FieldInfo field, OwnerSyncData source, OwnerSyncData target)
        {
            object sourceEntity = field.GetValue(source);
            object targetEntity = field.GetValue(target);

            // 若源字段为null，直接跳过
            if (sourceEntity == null) return;

            // 若目标字段为null，先创建空实例
            if (targetEntity == null)
            {
                targetEntity = Activator.CreateInstance(field.FieldType);
                field.SetValue(target, targetEntity);
            }

            // 反射获取所有字段，并赋值非null值
            FieldInfo[] entityFields = field.FieldType.GetFields(BindingFlags.Public | BindingFlags.Instance);
            foreach (FieldInfo entityField in entityFields)
            {
                object sourceValue = entityField.GetValue(sourceEntity);
                if (sourceValue != null)
                {
                    entityField.SetValue(targetEntity, sourceValue);
                }
            }
        }

        /// <summary>
        /// 同步 List<BaseMultiEntity子类> 字段
        /// </summary>
        private void SyncBaseMultiEntityList(FieldInfo field, OwnerSyncData source, OwnerSyncData target)
        {
            IList sourceList = field.GetValue(source) as IList;
            IList targetList = field.GetValue(target) as IList;

            // 初始化目标列表
            if (targetList == null)
            {
                targetList = (IList)Activator.CreateInstance(field.FieldType);
                field.SetValue(target, targetList);
            }

            // 处理删除操作（ID为负的项）
            ProcessDeleteOperations(sourceList, targetList);

            // 处理新增/更新操作（ID为正的项）
            ProcessAddOrUpdateOperations(sourceList, targetList);
        }

        /// <summary>
        /// 删除目标列表中ID为 |负ID| 的项
        /// </summary>
        private void ProcessDeleteOperations(IList sourceList, IList targetList)
        {
            if (sourceList == null) return;

            HashSet<long> deleteIds = new HashSet<long>();
            foreach (var sourceItem in sourceList.OfType<BaseMultiEntity>())
            {
                if (sourceItem.id < 0)
                {
                    deleteIds.Add(-sourceItem.id.Value);
                }
            }

            // 倒序删除避免索引错位
            for (int i = targetList.Count - 1; i >= 0; i--)
            {
                var targetItem = (BaseMultiEntity)targetList[i];
                if (deleteIds.Contains(targetItem.id ?? 0))
                {
                    targetList.RemoveAt(i);
                }
            }
        }

        /// <summary>
        /// 新增/更新目标列表中的项（仅赋值非null字段）
        /// </summary>
        private void ProcessAddOrUpdateOperations(IList sourceList, IList targetList)
        {
            if (sourceList == null) return;

            foreach (BaseMultiEntity sourceItem in sourceList.OfType<BaseMultiEntity>())
            {
                if (sourceItem.id <= 0) continue;

                // 查找目标列表中相同ID的项
                BaseMultiEntity targetItem = targetList.OfType<BaseMultiEntity>()
                    .FirstOrDefault(t => t.id == sourceItem.id);

                if (targetItem != null)
                {
                    // 更新现有项的非null字段
                    UpdateEntityFields(sourceItem, targetItem);
                }
                else
                {
                    // 创建新项并赋值所有字段（包括null）
                    targetItem = Activator.CreateInstance(sourceItem.GetType()) as BaseMultiEntity;
                    UpdateEntityFields(sourceItem, targetItem, copyNull: true);
                    targetList.Add(targetItem);
                }
            }
        }

        /// <summary>
        /// 将源实体的非null字段赋给目标
        /// </summary>
        private void UpdateEntityFields(BaseMultiEntity source, BaseMultiEntity target, bool copyNull = false)
        {
            FieldInfo[] fields = source.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
            foreach (FieldInfo field in fields)
            {
                object sourceValue = field.GetValue(source);
                if (copyNull || sourceValue != null)
                {
                    field.SetValue(target, sourceValue);
                }
            }
        }
    }
}